package com.jucai.pppeiyouclient.view.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.jucai.pppeiyouclient.MainActivity;
import com.jucai.pppeiyouclient.R;
import com.jucai.pppeiyouclient.base.BaseTakePhotoActivity;
import com.jucai.pppeiyouclient.base.PermissionListener;
import com.jucai.pppeiyouclient.base.TokenParam;
import com.jucai.pppeiyouclient.comm.CommonData;
import com.jucai.pppeiyouclient.comm.CommonMethod;
import com.jucai.pppeiyouclient.comm.CommonRequestNetData;
import com.jucai.pppeiyouclient.utils.ActivityCollector;
import com.jucai.pppeiyouclient.utils.CompressPhoto;
import com.jucai.pppeiyouclient.utils.ImageHandleUtils;
import com.jucai.pppeiyouclient.utils.LogUtils;
import com.jucai.pppeiyouclient.utils.OssUtils;
import com.jucai.pppeiyouclient.utils.TextCheckUtils;
import com.jucai.pppeiyouclient.utils.ToastUtils;
import com.jucai.pppeiyouclient.view.popup.HeadUploadPopup;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class AuthenticateActivity extends BaseTakePhotoActivity {

    private static final int TAKE_PHOTO = 2001;
    private static final int CHOOSE_IMAGE = 2002;
    private static final int CROP_IMAGE = 2003;

    private HeadUploadPopup headUploadPopup;

    private TextView authSKillName, authSubmit;
    private ImageView addSkillCertificate;
    private EditText authDesc;

    private String id, name;
    private String objectKey = "";
    private boolean avatarBoolean;
    private File imageStore = new File(Environment.getExternalStorageDirectory(),
            CommonData.STORAGE_PICTURE_HEAD_FILE + System.currentTimeMillis() + ".jpg");

    private boolean isImageUploading = false;

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_authenticate);
        ((TextView) findViewById(R.id.common_title_text)).setText("认证");
        authSKillName = (TextView) findViewById(R.id.auth_skill_name);
        authSubmit = (TextView) findViewById(R.id.auth_submit);
        addSkillCertificate = (ImageView) findViewById(R.id.add_skill_certificate);
        authDesc = (EditText) findViewById(R.id.auth_desc);
    }

    @Override
    protected void initData() {

        avatarBoolean = false;

        id = getIntent().getStringExtra("id");
        name = getIntent().getStringExtra("name");

        LogUtils.d(id + "|" + name);

        authSKillName.setText(name);

        /**
         * 初始化 popup
         */
        headUploadPopup = new HeadUploadPopup(this, getWindow(), R.style.animBottomInBottomOut,
                new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        headUploadPopup.dismiss();
                        switch (view.getId()) {
                            case R.id.upload_photo:
                                if (Build.VERSION.SDK_INT >= 23) {
                                    AuthenticateActivity.this.onRuntimePermissionRequest(new String[]{Manifest.permission.CAMERA},
                                            new PermissionListener() {
                                                @Override
                                                public void onGranted() {
                                                    ImageHandleUtils.takePhoto(AuthenticateActivity.this, imageStore, TAKE_PHOTO);
                                                }

                                                @Override
                                                public void onDenied(List<String> deniedPermissions) {
                                                    runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            ToastUtils.showToast("调起摄像头失败！");
                                                        }
                                                    });
                                                }
                                            });
                                } else
                                    ImageHandleUtils.takePhoto(AuthenticateActivity.this, imageStore, TAKE_PHOTO);

                                break;
                            case R.id.upload_album:
                                getTakePhoto().onPickMultiple(1);

//                                if (Build.VERSION.SDK_INT >= 23) {
//                                    //写SD卡权限申请
//                                    BaseActivity.onRuntimePermissionRequest(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
//                                            new PermissionListener() {
//                                                @Override
//                                                public void onGranted() {
//                                                    ImageHandleUtils.openAlum(AuthenticateActivity.this, CHOOSE_IMAGE);
//                                                }
//
//                                                @Override
//                                                public void onDenied(List<String> deniedPermissions) {
//                                                    for (String p : deniedPermissions) {
//                                                        Toast.makeText(ActivityCollector.getTopActivity(),
//                                                                p + "权限被拒绝", Toast.LENGTH_SHORT).show();
//                                                    }
//                                                }
//                                            });
//                                } else
//                                    ImageHandleUtils.openAlum(AuthenticateActivity.this, CHOOSE_IMAGE);

                                break;

                            case R.id.upload_cancel:
                                headUploadPopup.dismiss();
                                break;
                            default:
                                break;
                        }
                    }
                });

    }

    @Override
    protected void loadNetData() {

    }

    @Override
    protected void setListener() {

        findViewById(R.id.common_back).setOnClickListener(this);
        findViewById(R.id.common_home_back).setOnClickListener(this);
        addSkillCertificate.setOnClickListener(this);
        authSubmit.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_back:
                ActivityCollector.removeActivity(this);
                break;

            case R.id.common_home_back:
                startActivity(new Intent(AuthenticateActivity.this, MainActivity.class));
                ActivityCollector.removeActivity(this);
                break;

            case R.id.add_skill_certificate:
                if(isImageUploading){
                    ToastUtils.showToast("上传图片中，请稍后再试");
                    break;
                }
                headUploadPopup.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                CommonMethod.setWindowAlpha((float) 0.5, getWindow());
                break;

            case R.id.auth_submit:
                if(isImageUploading){
                    ToastUtils.showToast("上传图片中，请稍后再试");
                    break;
                }
                upload();
                break;

            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case TAKE_PHOTO:
                    showCropImage(data);
                    break;
//                case CHOOSE_IMAGE:
//                    ImageHandleUtils.startCropImage(AuthenticateActivity.this,
//                            data.getData(), CROP_IMAGE, 1, 1, 200, 200);
//                    break;
//                case CROP_IMAGE:
//                    if (data != null) {
//                        showCropImage(data);
//                    }
//                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
        uploadImage(result.getImages());
    }

    @Override
    public void takeFail(TResult result, String msg) {
        super.takeFail(result, msg);
    }


    private void uploadImage(ArrayList<TImage> images) {
        try {
            String photoPath = images.get(0).getCompressPath();
            if (TextUtils.isEmpty(photoPath))
                photoPath = images.get(0).getOriginalPath();

            objectKey = "temp/" + System.currentTimeMillis() + ".jpg";
            OssUtils.uploadPic(photoPath, objectKey, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                @Override
                public void onSuccess(PutObjectRequest putObjectRequest, PutObjectResult putObjectResult) {
                    isImageUploading = false;
                    avatarBoolean = true;
                }

                @Override
                public void onFailure(PutObjectRequest putObjectRequest, ClientException e, ServiceException e1) {
                    isImageUploading = false;
                    objectKey = "";
                    ToastUtils.showToast("头像上传失败！请稍后再试");
                }
            },new OssUtils.onPhotoUploadResult() {
                @Override
                public void onResult(String key, String filePath) {
                }

                @Override
                public void onProgress(long currentSize, long totalSize) {
                    if(currentSize >= totalSize){
                        isImageUploading = false;
                    }else{
                        isImageUploading = true;
                    }
                }
            });
            Glide.with(AuthenticateActivity.this).load(photoPath).skipMemoryCache(true).error(R.drawable.register_icon_head_default).into(addSkillCertificate);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showCropImage(Intent data) {

        try {
            Glide.with(this).load(imageStore.getPath()).into(addSkillCertificate);

            Bitmap compressPhoto = CompressPhoto.compressBySize(imageStore.getPath(),800,800);

            if (compressPhoto != null) {
                CompressPhoto.saveFile(compressPhoto, imageStore.getPath());
            }

            objectKey = "temp/" + System.currentTimeMillis() + ".jpg";
            OssUtils.uploadPic(imageStore.getPath(), objectKey, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                @Override
                public void onSuccess(PutObjectRequest putObjectRequest, PutObjectResult putObjectResult) {
                    isImageUploading = false;
                    avatarBoolean = true;
                }

                @Override
                public void onFailure(PutObjectRequest putObjectRequest, ClientException e, ServiceException e1) {
                    isImageUploading = false;
                    objectKey = "";
                    ToastUtils.showToast("头像上传失败！请稍后再试");
                }
            },new OssUtils.onPhotoUploadResult() {
                @Override
                public void onResult(String key, String filePath) {
                }

                @Override
                public void onProgress(long currentSize, long totalSize) {
                    if(currentSize >= totalSize){
                        isImageUploading = false;
                    }else{
                        isImageUploading = true;
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    private void upload() {

        if (TextCheckUtils.isEmpty(authDesc.getText().toString())) {
            ToastUtils.showToast("请输入描述");
            return;
        }
//
//        if (!avatarBoolean) {
//            ToastUtils.showToast("请上传资格证");
//            return;
//        }

        TokenParam tokenParam = new TokenParam(this, "Accompany_Skill.updateSkillCert");
        List<String> stringList = new ArrayList<>();
        stringList.add(objectKey);
        tokenParam.put("skill_cert_img", new Gson().toJson(stringList).replace("\"", "").replace("[", "").replace("]", ""));
        tokenParam.put("skill_cert_description", authDesc.getText().toString());
        tokenParam.put("skill_cert_id", id);

        LogUtils.d(tokenParam.getParam().toString());

        CommonRequestNetData.getJsonStringData(this, tokenParam.getParam(), true, new CommonRequestNetData.JsonStringCallBack() {
            @Override
            public void parseJsonString(String str) {
                LogUtils.d(str);
                ToastUtils.showToast("提交成功");
                ActivityCollector.removeActivity(AuthenticateActivity.this);
            }
        });

    }

}
